﻿using System;
using System.IO;
using System.Text;

namespace ConsoleAppIO
{
    class Program
    {
        static void Main(string[] args)
        {
            //实例化目录
            DirectoryInfo directoryInfo = new DirectoryInfo("D:\\Test1");
            directoryInfo.Create();                //创建目录
            directoryInfo.CreateSubdirectory("test01");//在text目录下创建子目录
            directoryInfo.CreateSubdirectory("text02");

            // 判断是否存在Test文件夹，如果不存在则创建该文件夹。
            bool a = Directory.Exists("D:\\Test2");
            if (a == false)
            {
                Directory.CreateDirectory("D:\\Test2");
                Console.WriteLine("操作成功");
            }

            DirectoryInfo directoryInfo1 = new DirectoryInfo("D:\\cs"); //创建文件夹
            directoryInfo1.Create();
             FileInfo file1 = new FileInfo("D:\\cs\\cs.html");//在D盘的Test2文件夹里创建一个test.html的文件
            file1.Create().Close();
            //定义文件路径
            string pash = "D:\\cs\\cs.html";
            //创建文件
            FileStream file = File.Create(pash);
            //获取文件信息
            Console.WriteLine("创建文件的时间" + File.GetCreationTime(pash));
            Console.WriteLine("文件最后被写入时间" + File.GetLastWriteTime(pash));
            //关闭流
            file.Close();
            Console.WriteLine("操作成功");

            //定义文件夹路径
            string path = "D:\\cs1\\students.txt";
            //实例化FileStream
            FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
            //定义名字
            string name = "小萝卜头";

            //转换为字节数组
            byte[] byte1 = Encoding.UTF8.GetBytes(name);

            //写入
            fileStream.Write(byte1);

            fileStream.Flush();
            fileStream.Close();
            Console.WriteLine("操作成功");


            //读取文件
            if (File.Exists(path))
            {
                //实例文件流
                FileStream fileStream1 = new FileStream(path, FileMode.Open, FileAccess.Read);
                //定义存放字节信息的数组长度
                byte[] bytes = new byte[fileStream1.Length];
                //读取信息
                fileStream1.Read(bytes, 0, bytes.Length);
                //将得到的字节型数组重写编码为字符型数组
                char[] c = Encoding.UTF8.GetChars(bytes);

                Console.WriteLine("学生的学号为：");
                Console.WriteLine(c);

                fileStream1.Flush();
                fileStream1.Close();
                Console.WriteLine("操作成功");

            }
            else
            {
                Console.WriteLine("该文件不存在");
            }
        }
    }
}
